<?php


if (! defined ( 'BASEPATH' )) exit ( 'No direct script access allowed' );
	/*
 * * etc: 公共函数
 * * author: deepe.xiao
 * * update: 2018-10-10
 */
 
use Core\Controller;

// 调用第三方文件
function loadSDK($file) {
	if (strlen ( $file ) != 0) {
		$result = include(FCPATH . "/app/libraries/" . $file . ".php");
	}
	return $result;
}

// 调用第三方类
function loadLibrary($class) {
	if (strlen ( $class ) != 0) {
		include_once (FCPATH . "/app/libraries/" . $class . ".php");
//		$class = "app\\libraries\\".$class;
		$obj = new $class ();

	}
	return $obj;
}

// 加载配置文件
function config_item($param) {
	static $_config;
	
	if (empty ( $_config )) {
		$config = include FCPATH . 'app/config/config.php';
		$_config = $config;
	}
	
	return $_config [$param];
}

// 记录日志
function log_msg($type, $message) {
	$flag = false;
	foreach ( config_item ( 'log_type' ) as $item ) {
		if ($item == $type) {
			$flag = true;
		}
	}
	if (! $flag) {
		view_log ( 'Type Error', 'The array log_type did not include this item <font color="red">' . $type . '</font>' );
		return false;
	}
	include_once (BASEPATH . "deepe.log.php");
	$log = new Log ();
	$log->write_log ( $type, $message );
}

// 页面显示
function view_log($heading = "", $message = "") {
	if (strlen ( $heading ) != 0) {
//		exit;
		include_once (BASEPATH . "deepe.error.php");
	}
}

if (! function_exists ( 'gzdecode' )) {
	function gzdecode($data) {
		return gzinflate ( substr ( $data, 10, - 8 ) );
	}
}

if (! function_exists ( 'array_column' )) {
	function array_column($input, $columnKey, $indexKey = null) {
		$columnKeyIsNumber = (is_numeric ( $columnKey )) ? true : false;
		$indexKeyIsNull = (is_null ( $indexKey )) ? true : false;
		$indexKeyIsNumber = (is_numeric ( $indexKey )) ? true : false;
		$result = array ();
		foreach ( ( array ) $input as $key => $row ) {
			if ($columnKeyIsNumber) {
				$tmp = array_slice ( $row, $columnKey, 1 );
				$tmp = (is_array ( $tmp ) && ! empty ( $tmp )) ? current ( $tmp ) : null;
			} else {
				$tmp = isset ( $row [$columnKey] ) ? $row [$columnKey] : null;
			}
			if (! $indexKeyIsNull) {
				if ($indexKeyIsNumber) {
					$key = array_slice ( $row, $indexKey, 1 );
					$key = (is_array ( $key ) && ! empty ( $key )) ? current ( $key ) : null;
					$key = is_null ( $key ) ? 0 : $key;
				} else {
					$key = isset ( $row [$indexKey] ) ? $row [$indexKey] : 0;
				}
			}
			$result [$key] = $tmp;
		}
		return $result;
	}
}
function getIp() {
	$cip = "";
	
	if (! empty ( $_SERVER ["HTTP_CLIENT_IP"] )) {
		$cip = $_SERVER ["HTTP_CLIENT_IP"];
	} elseif (! empty ( $_SERVER ["HTTP_X_FORWARDED_FOR"] )) {
		$cip = $_SERVER ["HTTP_X_FORWARDED_FOR"];
	} elseif (! empty ( $_SERVER ["REMOTE_ADDR"] )) {
		$cip = $_SERVER ["REMOTE_ADDR"];
	}
	
	return $cip;
}
function objectToArray($e) {
	$e = ( array ) $e;
	foreach ( $e as $k => $v ) {
		if (gettype ( $v ) == 'resource')
			return;
		if (gettype ( $v ) == 'object' || gettype ( $v ) == 'array')
			$e [$k] = ( array ) objectToArray ( $v );
	}
	return $e;
}
function curl($url, $need_useragent, $postFields = null) {
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	
	if ($need_useragent) {
		$user_agent = array (
				'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)',
				'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)',
				'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12',
				'Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13',
				'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
				'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; Sleipnir/2.9.8)',
				'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)',
				'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)',
				'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)',
				'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)',
				'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)',
				'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; ARM; Trident/6.0)',
				'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',
				'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)',
				'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
				'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
				'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
				'Opera/9.80 (Macintosh; Intel Mac OS X; U; en) Presto/2.2.15 Version/10.10',
				'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36' 
		);
		curl_setopt ( $ch, CURLOPT_USERAGENT, $user_agent [rand ( 0, 18 )] );
	}
	
	if (is_array ( $postFields ) && 0 < count ( $postFields )) {
		$postBodyString = "";
		foreach ( $postFields as $k => $v ) {
			$postBodyString .= "$k=" . urlencode ( $v ) . "&";
		}
		unset ( $k, $v );
		
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
		curl_setopt ( $ch, CURLOPT_POST, true );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, substr ( $postBodyString, 0, - 1 ) );
	}
	curl_setopt ( $ch, CURLOPT_VERBOSE, TRUE );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
	// curl_setopt($ch, CURLOPT_COOKIE, 'v=0; cookie2=146f00b8e13d6a262f8eacf768d673fc; t=1d892829834c12260f80e55580cd24bf');
	curl_setopt ( $ch, CURLOPT_TIMEOUT, 20 );
	
	$reponse = curl_exec ( $ch );
	curl_close ( $ch );
	return $reponse;
}

/**
 *
 * 微信要用到的CURL访问HTTPS
 *
 * @return json $data
 */
function wxcurl($url, $parameters = null) {
	
	// 初始化curl
	$ch = curl_init ();
	// 设置超时
	curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
	curl_setopt ( $ch, CURLOPT_HEADER, FALSE );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
	if (! empty ( $parameters )) {
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, urldecode ( $parameters ) );
	}
	// 运行curl，结果以json形式返回
	$res = curl_exec ( $ch );
	curl_close ( $ch );
	$data = json_decode ( $res, true );
	return $data;
}
function getTaobaoApi($postFields) {
	$result = null;
	
	if (is_array ( $postFields )) {
		$api_url = config_item ( 'api_url' );
		$remote_data = curl ( $api_url, $postFields );
		$result = json_decode ( $remote_data, TRUE );
		
		if (empty ( $result )) {
			$result = array ();
		}
	}
	
	return $result;
}
function getTopData($req, $session_key = '') {
	$c = new TopClient ();
	$c->appkey = config_item ( 'appKey' );
	$c->secretKey = config_item ( 'appSecret' );
	$c->format = 'json';
	$top_session = $session_key;
	if ((empty ( $session_key )) || ($top_session != 123)) {
		$top_session = empty ( $_SESSION ['top_session'] ) ? '' : $_SESSION ['top_session'];
	} else {
		$top_session = '';
	}
	$resp = $c->execute ( $req, $top_session );
	return $resp;
}
function getWeekDate() {
	$weekso = array ();
	$weeki = 0;
	for($i = 1; $i <= 7; $i ++) {
		$weekso [$weeki] ['week'] = getWeek ( date ( "Y-m-d", strtotime ( "+$i day" ) ) );
		$weekso [$weeki] ['weekNum'] = date ( "w", strtotime ( "+$i day" ) );
		$weekso [$weeki] ['day'] = date ( "Y-m-d", strtotime ( "+$i day" ) );
		$weeki ++;
	}
	$weekso = json_encode ( $weekso );
	return $weekso;
}
function getWeek($time) {
	$week = date ( "w", strtotime ( $time ) );
	switch ($week) {
		case 1 :
			return "周一";
			break;
		case 2 :
			return "周二";
			break;
		case 3 :
			return "周三";
			break;
		case 4 :
			return "周四";
			break;
		case 5 :
			return "周五";
			break;
		case 6 :
			return "周六";
			break;
		case 0 :
			return "周日";
			break;
	}
}
function loadTop() {
	require_once (FCPATH . '/app/libraries/top/RequestCheckUtil.php');
	require_once (FCPATH . '/app/libraries/top/TopClient.php');
}

// validate token ,author by deepe.xiao
// date: 2016-03-05
/*
 * input params :
 * 1、params: 每个接口固定需要传的参数集合
 * 2、spm: 渠道ID.版本号(只能为3个字符，即x.x).用户ID.时间戳(小时 , 24小时制).是否需要验证用户( 0 , 1 )
 * 3、bobao_token: 播报哥签名，固定32位，md5。
 * 组合方式：bobao_token = md5( 接口固定参数+时间戳(小时)+key+渠道ID )
 *
 * out params : 1 / 负数
 * bobao_token 3个小时内有效(可配置)
 *
 * //testURL:http://bobaoge.localhost/?action=admin&func=index
 *
 */
function validateToken($params = array()) {
	// 测试数据
	// $testP = config_item('bobaoge_interface_key');
	// $params = array(
	// "action" => 'user',
	// "func" => 'userLogin',
	// "userName" => '发疯的',
	// 'passWord' => 'aaa的',
	// "spm" => 'abbg230i.1.6.5.1457600400.1',
	// // "token_key" => $testP['token_key'],
	// "bobao_token" => md5( 'useruserLoginbobaogeHongHe3V1drzrT1发疯的aaa的' )
	// );
	
	$version = reviewVersionCode( $params['spm'] );
	$bobao_params = config_item ( 'bobaoge_interface_key' );
	$params ['token_key'] = $bobao_params ['token_key'][$version];
	
	// echo '123456abbg230i.1.6.15.1457481600.1'.$testP['token_key'].'deepeuseruserLogin<br/>';
                  
	$code = $message = '';
	try {
		if (count ( $params ) <= 2) {
			$code = - 99001001;
			$message = "Sorry , Must input params > 2";
			throw new Exception ( json_encode ( array (
					'code' => $code,
					'message' => $message 
			) ) );
		} else if (! (isset ( $params ['spm'] ))) {
			$code = - 99001002;
			$message = "Sorry , Must input spm";
			throw new Exception ( json_encode ( array (
					'code' => $code,
					'message' => $message 
			) ) );
		} else if (! (isset ( $params ['bobao_token'] ))) {
			$code = - 99001003;
			$message = "Sorry , Must input bobao_token";
			throw new Exception ( json_encode ( array (
					'code' => $code,
					'message' => $message 
			) ) );
		} else {
			$spm = $params ['spm'];
			unset ( $params ['spm'] );
			$bobao_token = $params ['bobao_token'];
			unset ( $params ['bobao_token'] );
			$spm_array = explode ( ".", $spm );
			// if (count ( $spm_array ) == 6) {
			if (count ( $spm_array ) == 6||count ( $spm_array ) == 7) {
				$sourceID = $spm_array [0];
				if(count ( $spm_array ) == 6){
					$version = $spm_array [1] . "." . $spm_array [2];
					$user_id = isset($params['userid']) ? $params['userid'] : $spm_array [3];
					$time = $spm_array [4];
					$is_valid_user = $spm_array [5];
				}else{
					$version = $spm_array [1] . "." . $spm_array [2]. "." . $spm_array [3];
					$user_id = isset($params['userid']) ? $params['userid'] : $spm_array [4];
					$time = $spm_array [5];
					$is_valid_user = $spm_array [6];
				}	
				//降权
				$retd = userDown($version,$user_id);		
				// if( in_array( $sourceID, $source_array )){
				if ( isValidVersion ( $version ) ) {
					if (isValidUser ( $user_id, $is_valid_user )) {
						if ($result = isValidTime ( $time )) {
							// 接口固定参数+时间戳(小时)+key+渠道ID
							$params ['sourceID'] = $sourceID;
							$params ['time'] = $time;
							
							// 要进行排序的字段
							$params_ascii = array_keys ( $params );
							sort ( $params_ascii, SORT_REGULAR );
							
							// log_msg('general','排序后的字段:>>>'.json_encode($params_ascii));
							$param_str = '';
							foreach ( $params_ascii as $kt => $vt ) {
								// echo $vt;die();
								$param_str .= $params [$vt];
							}
							// log_msg('general','组合的结果:>>>'. $param_str);
							
							if ($bobao_token == md5 ( $param_str )) {
								return $retd;
							} else {
								$code = - 99001009;
								$message = "Sorry , param token is error";
								throw new Exception ( json_encode ( array (
										'code' => $code,
										'message' => $message 
								) ) );
							}
						} else {
							$code = - 99001008;
							$message = "Sorry , param time is error";
							throw new Exception ( json_encode ( array (
									'code' => $code,
									'message' => $message 
							) ) );
						}
					} else {
						$code = - 99001007;
						$message = "Sorry , param user_id is error";
						throw new Exception ( json_encode ( array (
								'code' => $code,
								'message' => $message 
						) ) );
					}
				} else {
					$code = - 99001006;
					$message = "Sorry , param version is error";
					throw new Exception ( json_encode ( array (
							'code' => $code,
							'message' => $message 
					) ) );
				}
				// }else{
				// $code = -99001005;
				// $message = "Sorry , param source_id is error";
				// throw new Exception( json_encode( array( 'code' => $code , 'message' => $message ) ) );
				// }
			} else {
				$code = - 99001004;
				$message = "Sorry , param spm is error";
				throw new Exception ( json_encode ( array (
						'code' => $code,
						'message' => $message 
				) ) );
			}
		}
	} catch ( Exception $e ) {
		// return $code;
		print $e->getMessage ();
		die ();
	}
}
//判断是否需要降级
function userDown($version,$userId){

	$c = new Controller ();
	$userModel = $c->loadModel ( 'user', true );
	$userResult = $userModel->searchUserDown($userId);
    $nowTime = strtotime(date("Y-m-d H:i:s"));
	if(!empty($userResult)){
		if($version>=4.0){
			$time = strtotime($userResult[0]['down_time'])+$userResult[0]['down_date']*3600;
			if(!empty($userResult)){
				if($nowTime<$time){
					if($userResult[0]['down_state']==1){
						$code = 2;
						$down = $code."-".$time;
					}else{
						//永久降权
						$code = 3;
						$down = $code."-".$time;
					}	
				}else{
					if($userResult[0]['down_state']==1){
						$userModel->updateUserDownState($userId);
						$code = 1;
						$down = $code."-".$time;
					}else{
						//永久降权
						$code = 3;
						$down = $code."-".$time;
					}
				}
			}else{
				$code = 1;
				$down = $code."-".$time;
			}
			return $down;
		}else{
			return 1;
		}
	}else{
		return 1;
	}	
}	
// 判断版本(向下兼容，不能大于当前版本)
function isValidVersion($version) {
	$bobaoKey = config_item ( 'bobaoge_interface_key' );
	if ($bobaoKey ['isValidVersion'] == 1) {
		$c = new Controller ();
		$versionModel = $c->loadModel ( 'version', true );
		$result = $versionModel->searchVersion ();
		if ($version <= floatval ( $result [0] ['version_name'] )) {
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}

// 判断用户是否存在(可配置)
function isValidUser($user_id, $is_valid_user) {
	if (intval ( $is_valid_user ) > 0 || $user_id != 0) {
		$c = new Controller ();
		$userModel = $c->loadModel ( 'user', true );
		$result = $userModel->searchUserByUserId ( $user_id );
		return $result;
	} else {
		return true;
	}
}

// 判断客户端的时间是否跟服务端的时间在X个小时之内
function isValidTime($time) {
	$date = date ( 'Y-m-d H:00:00' );
	$bobaoKey = config_item ( 'bobaoge_interface_key' );
	
	if ($bobaoKey ['isValidTime'] == 1) {
		$times = array ();
		for($i = abs ( $bobaoKey ['overtimeHour'] ['minhour'] ); $i >= 0; $i --) {
			$times [] = strtotime ( $date . "-$i hours" );
			// echo strtotime( $date . "-$i hours");
			// echo date('Y-m-d H',strtotime( $date . "-$i hours")) ."<br/>";
		}
		
		for($i = 1; $i <= $bobaoKey ['overtimeHour'] ['maxhour']; $i ++) {
			$times [] = strtotime ( $date . "+$i hours" );
			// echo date('Y-m-d H',strtotime( $date . "+$i hours")) ."<br/>";
		}
		
		if (in_array ( $time, $times )) {
			return $time;
		} else {
			return false;
		}
	} else {
		return true;
	}
}

function authority($authority_name,$id) {
	$code=$message="";
	$c = new Controller ();
	$authorityModel = $c->loadAdminModel ( 'authority', true );
	$resultMaster = $authorityModel->searchMaster ( $id );
	$result = $authorityModel->searchIsAuthority ( $resultMaster );
	$arr = array ();
	foreach ( $result as $k => $v ) {
		foreach ( $v as $key => $value ) {
			$arr [] = $value ["authority_name"];
		}
	}

	// var_dump($authority_name);die();
	if (in_array ( $authority_name, $arr )) {
		$logModel = $c->loadAdminModel ( 'adminlog', true );
		$logModel->addAdminLog( 
				$_SESSION['user']['admin_account'] , getIp(),
				"", $authority_name, 
				2, "v1.0" );
		return $result;
	} else {
		$code = - 99001009;
		$message = "Sorry , You do not have permission to access";
		throw new Exception ( json_encode ( array (
				'code' => $code,
				'message' => $message 
		) ) );
	}
}



//复查当前版本号是否支持
//spm：spm码
function reviewVersionCode( $spm ){
	$spVersion = config_item( 'sp_version' );
	$clientVersion = "";
	if( $spm == "" ){
		$clientVersion = $spVersion[0];
	}else{
		$spm = explode( ".", $spm );
		$clientVersion = strval($spm[1].".".$spm[2]);
		$clientVersion = str_replace( ".", "_", $clientVersion );
	}
	
	$code = $message = '';
	try {
		if( in_array( $clientVersion , $spVersion ) ){
			return $clientVersion;
		}
		
		if( $clientVersion == '1_70' ){
			return '1_7';
		}
	}catch ( Exception $e ) {
		// return $code;
		print $e->getMessage ();
		die ();
	}	
}

//提供JPush极光推送消息
function jpushMessage( $alias = "", $tags = array(), $title , $message , $extra = array() ){
	if( config_item('jpush_test') ){ 
		$alias = "test_".$alias;
	}else{
		$alias = "live_".$alias;
	}
	$client = loadSDK( "JPush" );
	// 完整的推送示例,包含指定Platform,指定Alias,Tag,指定iOS,Android notification,指定Message等
	$cl = $client['obj'];
	$result = $cl->push()
		->setPlatform(array('ios', 'android'));
		if( $alias != ""){ $result = $result->addAlias($alias); }
		if( count($tags) > 0 ){ $result = $result->addTag(array('tag1', 'tag2')); }
		
	 $result = $result->setNotificationAlert('【播报哥】')
			->addAndroidNotification( $message, 
				$title, 
				1, 
				$extra
				)
			->addIosNotification($message, 
				$title, 
				$client['bage'], 
				true, 
				'iOS category', 
				$extra)
		->setMessage("msg content", 'msg title', 'type', array("key1"=>"value1", "key2"=>"value2"))
			->setOptions(100000, 3600, null, false)
			->send();
			
	//$logModel->noticeLog( $notice );
	//echo 'Result=' . json_encode($result);
	//推送日志，存msg_id
}
//提供JPush极光推送消息
function jpushPrintMessage( $alias = "", $tags = array(), $title , $message , $extra = array() ){
	if( config_item('jpush_test') ){ 
		$alias = "test_".$alias;
	}else{
		$alias = "live_".$alias;
	}
	$client = loadSDK( "JPushprint" );
	// 完整的推送示例,包含指定Platform,指定Alias,Tag,指定iOS,Android notification,指定Message等
	$cl = $client['obj'];
	$result = $cl->push()
		->setPlatform(array('ios', 'android'));
		if( $alias != ""){ $result = $result->addAlias($alias); }
		if( count($tags) > 0 ){ $result = $result->addTag(array('tag1', 'tag2')); }
		
	 $result = $result->setNotificationAlert('【制版平台】')
			->addAndroidNotification( $message, 
				$title, 
				1, 
				$extra
				)
			->addIosNotification($message, 
				$title, 
				$client['bage'], 
				true, 
				'iOS category', 
				$extra)
		->setMessage("msg content", 'msg title', 'type', array("key1"=>"value1", "key2"=>"value2"))
			->setOptions(100000, 3600, null, false)
			->send();
			
	//$logModel->noticeLog( $notice );
	//echo 'Result=' . json_encode($result);
	//推送日志，存msg_id
}
function sendPayUserSMS( $message_contents, $message_id , $cid ){
	$c = new Controller ();
	$userModel = $c->loadModel ( 'pay', true , config_item('pj_name').'_2_0' );
	$result = $userModel->paySendUser ( $cid );
	//发送推送消息
	$MessageModel = $c->loadAdminModel ( 'message', true );
	$rs = $MessageModel->searchMessageList ( array (
		'p_keyValue' => "",
		'p_categoryLevel2ID' => "",
		'p_zoneIDs' => "",
		'p_userID' => 0,
		'p_state' => '',
		'p_curPage' => 1,
		'p_pageSize' => 10,
		'p_sort' => "message_state ASC, message_date DESC",
		'p_messageID' => $message_id
	));
	$zoneMsg = $MessageModel->searchZone();
	if( $result ){ 
		$rs[0]['push_type'] = 2;
		$rs[0]['isLaud'] = 0;
		$rs[0]['msgtype'] = 1;
		$rs[0]['messge_msg_id'] = $rs[0]['message_id'];
		$len = 15;
		$writeId = 4;
		$tend = $MessageModel->searchWrite($writeId);
		$rs[0]['write_title'] = $tend[0]['write_title'];
		$rs[0]['write_content'] = $tend[0]['write_content'];
		foreach($zoneMsg as $key=>$value){
			if($value['zone_id']==$rs[0]['message_zone_id']){
				$rs[0]['zone_name'] = $value['zone_name'];
			}	
		}	
		$content = left( $message_contents , 0 , $len );
		
		if( mb_strlen($message_contents) > $len ){
			$content .= "...";
		
		}
		$result = array_reduce($result, create_function('$v,$w', '$v[$w["user_id"]]=$w["user_id"];return $v;'));
		$result = array_keys( $result );
		foreach( $result as $val ){
			$searchCerMsg= $MessageModel->searchCerMessage($val);
			// print_r("<pre>");
		// print_r($searchCerMsg);die();
			if(!empty($searchCerMsg)){
				foreach($searchCerMsg as $key=>$value){
					$compt = $MessageModel->searchComName($value['cer_type'],$value['cer_search_id']);
					if($value['cer_type']==1){
						$searchCerMsg[$key]['comMsg']['head'] = $compt[0]['cer_person_headimg'];
						$searchCerMsg[$key]['comMsg']['cer_user_nickname'] = $compt[0]['cer_user_nickname'];
					}else{
						$searchCerMsg[$key]['comMsg']['head'] = $compt[0]['cer_company_headimg'];
						$searchCerMsg[$key]['comMsg']['cer_user_nickname'] = $compt[0]['cer_company_name'];
					}	
				}	
				// print_r("<pre>");
			// print_r($searchCerMsg);die();
				foreach($searchCerMsg as $key=>$value){
					$searchLvPoint = $MessageModel->searchPoint($value['cer_msg_id']);
					// foreach($searchLvPoint as $k=>$v){
						// if($value['cer_level_id']==$v['cer_level_id']){
					$cerTime = strtotime($value['cer_msg_verfiy']);
					$cerTime = date("Y-m-d H:i:s",$cerTime);
					$nowTime = date("Y-m-d H:i:s");
					$searchCerMsg[$key]['point'][] = $searchLvPoint[0]['cer_aut_name'].","."第".($nowTime-$cerTime+1)."年认证";	
						// }
					// }
				}
				// print_r("<pre>");
			// print_r($searchCerMsg);die();
				
				foreach ($rs as $msgkey => $result_message) {
					foreach($searchCerMsg as $k=>$v){
						if($result_message['message_user_id']==$v['cer_user_id']){
							$rs[$msgkey]['point'] = $v['point'];
							$rs[$msgkey]['cerMessage'] = $v['comMsg'];
						}	
					}
				}
			}	
			jpushMessage( $val , 
				array(), 
				'【播报哥】订阅消息', 
				$content, 
				$rs[0]
			);
		}
		/*$content .= " 点击查看完整信息 http://dwz.cn/3ZY3g5 .";
		                               
		$phones = implode( "," ,  array_keys( $result ));
		$url = "http://m.5c.com.cn/api/send/index.php?username=%s&password_md5=%s&apikey=%s&mobile=%s&content=%s&encode=UTF-8";
		$content = urlencode($content);	//对中文进行编码，否则无法发送
		$config = config_item( 'message' );
		$resultUrl = sprintf( $url, $config['username'], $config['password'] , $config['key'] , $phones, $content );

		$result = curl( $resultUrl , 1 );
		*/
	}
	return $rs;
}


function left($str, $start = 0 , $len, $charset="utf-8")
{
    //如果截取长度小于等于0，则返回空
    if( !is_numeric($len) or $len <= 0 )
    {
        return "";
    }

    //如果截取长度大于总字符串长度，则直接返回当前字符串
    $sLen = strlen($str);
    if( $len >= $sLen )
    {
        return $str;
    }
 
    //判断使用什么编码，默认为utf-8
    if ( strtolower($charset) == "utf-8" )
    {
        $len_step = 3; //如果是utf-8编码，则中文字符长度为3  
    }else{
        $len_step = 2; //如果是gb2312或big5编码，则中文字符长度为2
    } 

    //执行截取操作
    $len_i = 0; 
    //初始化计数当前已截取的字符串个数，此值为字符串的个数值（非字节数）
    $substr_len = 0; //初始化应该要截取的总字节数

    for( $i=0; $i < $sLen; $i++ )
    {
        if ( $len_i >= $len ) break; //总截取$len个字符串后，停止循环
        //判断，如果是中文字符串，则当前总字节数加上相应编码的中文字符长度
        if( ord(substr($str,$i,1)) > 0xa0 )
        {
            $i += $len_step - 1;
            $substr_len += $len_step;
        }else{ //否则，为英文字符，加1个字节
            $substr_len ++;
        }
    $len_i ++;
    }
    $result_str = substr($str,0,$substr_len );
    return $result_str;
}

/**
* @author: deepe.xiao
* @etc: all of money records
* @param: array
	1、tradeMoney 消费金额(*100)
	2、costType 收入支出类型（1 支出/ 2 收入）
	3、tradeType 消费类型（ 1 充值/ 2 订阅/ 3 发布消息/ 4 拼手气/ 5 打赏/6 信息分享红包/7 拼手气红包/8 管理员红包/9 拼手气虚拟商品/【10 用户已发布未通过消息退回】/【11 用户已发布删除消息退回】）
	4、payType 支付类型（1 微信/2 支付宝/3 余额）
	5、payUserPhone 消费用户手机
	6、payUserId 消费用户ID
	7、destUserId 目标用户ID
	8、destUserPhone 目标用户手机(可选)
	9、userBalance 当前用户余额
	10、destUserBalance 目标用户余额
	11、用户已发布删除消息退回
	12、广告支付
	13、结束广告投放
	14、广告续费
	15、实名认证
	16、广告拒绝
	17、推广余额不足退款
	18、充值广告余额
	19、充值广告余额（支付宝微信）
	20、制版下载扣费
    21、制版师提现
	22、续费广告余额
	23、爆款支付支付宝微信
	24、爆款支付余额支付
* @return: 
	1            成功
	-980010001  参数不完整
	-980010002  余额信息错误
	-980010003  costType类型错误
	-980010004  tradeType类型错误
	-980010005  payType类型错误
	-980010006  消费用户ID错误
	-980010007  目标用户ID错误
	-980010008  消费手机号码错误
	-980010009  目标用户手机错误	  
	-980010010  交易金额错误
	-980010011  收入的金额大于当前余额
*/
function recordsByTrade( $records = array() ){
	try{
		$code = 1;
		if( count( $records ) != 10 ){
			$code = -980010001;
			throw new Exception( $code );
		}else if( !isset( $records['userBalance'] ) ){
			$code = -980010002;
			throw new Exception( $code );
		}else if( $records['costType'] > 2 ){
			$code = -980010003;
			throw new Exception( $code );
		}else if( $records['tradeType'] > 24){
			$code = -980010004;
			throw new Exception( $code );
		}else if( $records['payType']  > 3 ){
			$code = -980010005;
			throw new Exception( $code );
		}else if( $records['tradeMoney'] <= 0 ){
			$code = -980010010;
			throw new Exception( $code );
		}else{
			$c = new Controller ();
			$balanceModel = $c->loadAdminModel ( 'balancerecords', true );
			$existResult = $balanceModel->searchUserExists( $records['payUserId'] , $records['payUserPhone'] );
			if( !$existResult ){
				$code = -980010006;
				throw new Exception( $code );
			}else{
				//判断如果是非余额支付则不计算判断
				if( $records['payType'] == 1 || $records['payType'] == 2 ){
					$balanceModel->insertBalanceRecords(
							array(
								'userId' => $records['payUserId'],
								'userPhone' => $records['payUserPhone'],
								'costType' => $records['costType'],
								'tradeType' => $records['tradeType'],
								'payType' => $records['payType'],
								'tradeMoney' => $records['tradeMoney'],
								'userBalance' => $records['userBalance']
							)
						);
				}else{
					$result = $balanceModel->searchBalanceRecords ( $records['payUserId'] );
	
					//发现用户之前有记录，判断消费金额和余额是否符合
					if( $result ){
						$result = $result[0];
						//支出
						if( $records['costType'] == 1 
							&& intval(strval($records['tradeMoney'])) != $result['user_balance'] - intval(strval($records['userBalance']))  ){
							$code = -980010002;
							throw new Exception( $code );
						}
						
						
						//收入
						else if( $records['costType'] == 2 
							&& intval(strval($records['userBalance'])) != $result['user_balance'] + intval(strval($records['tradeMoney']))  ){
							$code = -980010002;
							throw new Exception( $code );	
						}
					}else{
						if( $records['costType'] == 2  &&  intval(strval($records['userBalance']))  < intval(strval($records['tradeMoney']))){
							$code = -9800100011;
							throw new Exception( $code );
						}
					}

					//打赏
					if( $records['tradeType'] == 5  ){
						$existResult = $balanceModel->searchUserExists( $records['destUserId'], $records['destUserPhone'] );
						if( !$existResult ){
							$code = -980010007;
							throw new Exception( $code );	
						}else{
							$destResult = $balanceModel->searchBalanceRecords ( $records['destUserId'] );
							//发现用户之前有记录，判断消费金额和余额是否符合
							if( $destResult ){
								$destResult = $destResult[0];
								//收入
								if( intval(strval($records['destUserBalance'])) != intval(strval($destResult['user_balance'])) + intval(strval($records['tradeMoney'])) ){
									
									$code = -980010010;
									throw new Exception( $code );	
								}
							}
							
							//打赏人记录
							$balanceModel->insertBalanceRecords(
								array(
									'userId' => $records['payUserId'],
									'userPhone' => $records['payUserPhone'],
									'costType' => $records['costType'],
									'tradeType' => $records['tradeType'],
									'payType' => $records['payType'],
									'tradeMoney' => $records['tradeMoney'],
									'userBalance' => $records['userBalance']
								)
							);
							//被打赏人记录
							$balanceModel->insertBalanceRecords(
								array(
									'userId' => $records['destUserId'],
									'userPhone' => $records['destUserPhone'],
									'costType' => 2,
									'tradeType' => $records['tradeType'],
									'payType' => $records['payType'],
									'tradeMoney' => $records['tradeMoney'],
									'userBalance' => $records['destUserBalance']
								)
							);
						}
					}else{
						//非打赏记录
						$balanceModel->insertBalanceRecords(
							array(
								'userId' => $records['payUserId'],
								'userPhone' => $records['payUserPhone'],
								'costType' => $records['costType'],
								'tradeType' => $records['tradeType'],
								'payType' => $records['payType'],
								'tradeMoney' => $records['tradeMoney'],
								'userBalance' => $records['userBalance']
							)
						);
					}	
				}	
			}
			return $code;
		}	
	}catch(Exception $e){
		return $e->getMessage ();
	}
}


	
?>
